/*
 * @Author: Jiraiya
 * @Date: 2020-05-26 15:08:17
 * @LastEditors: Jiraiya
 * @LastEditTime: 2020-05-26 16:37:09
 * @Description: 
 */

/**
 * @description: 
 * @param {Function} reduce 一个函数，用来处理action对应的事件
 * @param {any} initState 初始state
 * @param {Function} rewriteCreateStoreFun 中间件
 * @return: 
 */
export default function createStore(reducer, initState, rewriteCreateStoreFun){
    if(typeof initState === 'function' && typeof rewriteCreateStoreFun === 'undefined'){
        rewriteCreateStoreFun = initState;
        initState = undefined;
    }

    if(rewriteCreateStoreFun){
        const newCreateStore = rewriteCreateStoreFun(createStore);
        return newCreateStore(reducer, initState);
    }

    let state = initState;
    let listeners = [];

    function subscribe(listener){
        listeners.push(listener);
        return function unsubscribe(){
            const index = listeners.indexOf(listener);
            listeners.splice(index, 1);
        }
    }

    function getState(){
        return state;
    }

    function dispatch(action){
        reducer(state, action);
        listeners.forEach(listener=>{
            listener()
        })
    }

    function replaceReducer(nextReducer) {
        reducer = nextReducer
        dispatch({ type: Symbol() });
    }

    dispatch({type: Symbol()})

    return {
        subscribe,
        dispatch,
        getState,
        replaceReducer,
    }
}